package bbk.nfc.persistent;

import bbk.nfc.opt.OptApp;
import bbk.nfc.opt.OptSetting;
import bbk.nfc.opt.Vars;
import bbk.nfc.widget.NfcToast;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

public class NfcPref
{
	public static final String TAG = "NFC_Pref";
	public static final String TASK_DIV = "\\$";//转义字符
	public static final String ACT_DIV = "@";
	
	private static NfcPref me = null;
	private Context mContext = null;
	private OptApp mOptApp = null;
	private SharedPreferences mSharePref;
	
	private NfcPref(Context context)
	{
		mContext = context;
		mOptApp = OptApp.getOptApp(mContext);
		mSharePref = PreferenceManager.getDefaultSharedPreferences(context);
	}
	
	public static NfcPref get(Context context)
	{
		if (me == null)
		{
			me = new NfcPref(context);
		}
		return me;
	}
	
	public static void release()
	{
		if (me != null)
		{
			me.mContext = null;
			me = null;
		}
	}
	
	public void processTask(int id)
	{
		String task = getPref(id);
		String action[] = decodeTask(task);
		for(String act:action)
		{
			String command[] = decodeAction(act);
			processAction(command);
		}
	}
	
	public void processAction(String command[])
	{
		byte r0[]=command[0].getBytes();
		int length = command.length;
		switch(r0[0])
		{
		case Vars.WIFI:
			NfcToast.showToast((Activity)mContext,"wifi");
			OptSetting.toggleWifi(r0[1], mContext);
			break;
		case Vars.BT:
			OptSetting.toggleBT(r0[1]);
			break;
		case Vars.GPS:
			OptSetting.toggleGPS(r0[1], mContext);
			break;
		case Vars.FLIGHT_MODE:
			OptSetting.toggleAirplaneMode(r0[1], mContext);
			break;
		case Vars.PHONE:
			if(length ==2)
			{
				NfcToast.showToast((Activity)mContext,"phone");
				mOptApp.callTel(command[1]);
			}
			break;
		case Vars.SMS:
			if(length ==3)
				mOptApp.sendMessage(command[1], command[2]);
			break;
		}
	}
	
	
	public void savePref(String task, int id)
	{
		Editor e = mSharePref.edit();
		e.putString(""+id, task);
		e.commit(); 
	}
	
	public String getPref(int id)
	{
		return mSharePref.getString(""+id, null);
	}
	
	public String codeAction(String[] s)
	{
		return code(s, ACT_DIV);
	}
	
	public String[] decodeAction(String s)
	{
		return decode(s, ACT_DIV);
	}
	
	public String codeTask(String[] s)
	{
		return code(s, TASK_DIV);
	}
	
	public String[] decodeTask(String s)
	{
		return decode(s, TASK_DIV);
	}
	
	private String code(String[] s, String div)
	{
		int l = s.length;
		String d = s[0];
		if (l > 1)
		{
			for (int i = 1; i < l; i++)
			{
				d += div;
				d += s[i];
			}
		}
		return d;
	}
	
	private String[] decode(String s, String div)
	{
		String[] d = s.split(div);
		return d;
	}
	
}
